﻿using jvm.rtda;
using jvm.rtda.frame;
using jvm.rtda.heap.pool;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jvm.native.java.io
{
    class UnixFileSystem
    {
        // jdk8中没有找到这个类
        static string classname = "java/io/UnixFileSystem";
        public static void Init()
        {
            NativeMethodPool.Register(classname, "canonicalize0", "(Ljava/lang/String;)Ljava/lang/String;", canonicalize0);
            NativeMethodPool.Register(classname, "getBooleanAttributes0", "(Ljava/io/File;)I", getBooleanAttributes0);
        }

        // private native String canonicalize0(String path) throws IOException;
        // (Ljava/lang/String;)Ljava/lang/String;
        static void canonicalize0(JFrame frame)
        {
            JLocalVars vars = frame.localVars;
            JObject path = vars.GetRef(1);
            JOperandStack stack = frame.operandStack;
            stack.PushRef(path);
        }

        // public native int getBooleanAttributes0(File f);
        // (Ljava/io/File;)I
        static void getBooleanAttributes0(JFrame frame)
        {
            JLocalVars vars = frame.localVars;
            JObject f = vars.GetRef(1);
            string path = _getPath(f);

            // todo
            int attributes0 = 0;
            if (_exists(path))
            {
                attributes0 |= 0x01;
            }
            if (_isDir(path))
            {
                attributes0 |= 0x04;
            }

            JOperandStack stack = frame.operandStack;
            stack.PushInt(attributes0);
        }

        static string _getPath(JObject fileObj)
        {
            JObject pathStr = fileObj.GetRefVar("path", "Ljava/lang/String;");
            return StringPool.String(pathStr);
        }

        // http://stackoverflow.com/questions/10510691/how-to-check-whether-a-file-or-directory-denoted-by-a-path-exists-in-golang
        // exists returns whether the given file or directory exists or not
        static bool _exists(string path)
        {
            return File.Exists(path);
        }

        // http://stackoverflow.com/questions/8824571/golang-determining-whether-file-points-to-file-or-directory
        static bool _isDir(string path)
        {
            return Directory.Exists(path);
        }

    }
}
